package com.zxbg.service.impl.systemtoolsServiceImpl;

import com.zxbg.dao.AppCategoryDao;
import com.zxbg.dao.AppDao;
import com.zxbg.dao.EmployeeDao;
import com.zxbg.domain.App;
import com.zxbg.domain.AppCategory;
import com.zxbg.domain.Employee;
import com.zxbg.service.systemtoolsService.ApplySortService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class ApplySortServiceImpl implements ApplySortService {
    @Autowired
    AppCategoryDao appCategoryDao;
    @Autowired
    AppDao appDao;
    @Autowired
    EmployeeDao employeeDao;

    @Override
    public List<AppCategory> getAllAppInCategory(Integer tenant_id, String employee_id) {
        return filterList(appCategoryDao.getAllCategory(tenant_id), tenant_id, null, employee_id);
    }

    @Override
    public List<AppCategory> getTargetCategoryApp(String key, Integer tenant_id, String employee_id) {
        return filterList(appCategoryDao.getAllCategory(tenant_id), tenant_id, key, employee_id);
    }

    public List<AppCategory> filterList(List<AppCategory> appCategoryList, Integer tenant_id, String key, String employee_id) {
        List<AppCategory> resList = new ArrayList<>();
        for (int i = 0; i < appCategoryList.size(); i++) {
            AppCategory temp = appCategoryList.get(i);
            List<App> tempAppList = new ArrayList<>();
            if(key == null) {
                tempAppList = appDao.getAppByCategoryId(temp.getCategory_id(), tenant_id);
            } else {
                tempAppList = appDao.getAppByCategoryIdAndName(temp.getCategory_id(), "%" + key.replace("\"", "") + "%", tenant_id);
            }
            if(tempAppList != null && tempAppList.size() > 0) {
                String selectedApp = employeeDao.getEmployeeByEmployeeId(employee_id, tenant_id).getSelected_app_id();
                if(selectedApp != null && !selectedApp.equals("")) {
                    for (App app : tempAppList) {
                        List<String> selectedAppList = Arrays.asList(selectedApp.split(","));
                        if(selectedAppList.contains(app.getApp_id())) {
                            app.setCollected(true);
                        } else {
                            app.setCollected(false);
                        }
                    }
                }
                temp.setApp_list(tempAppList);
                resList.add(temp);
            }
        }
        return resList;
    }

    @Override
    public boolean changeAppOrder(String app_id, Integer order, Integer tenant_id) {
        return appDao.changeAppOrder(app_id, order, tenant_id) > 0;
    }
}
